package com.smqj.icu;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class SqlLink {

    private static Logger logger = LogManager.getLogger(SqlLink.class.getName());

    private static String DB_URL;
    private static String DB_USER_NAME;
    private static String DB_PASSWORD;

    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection conn;
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        DB_URL = bundle.getString("jdbc.greenPlum.url");
        DB_USER_NAME = bundle.getString("jdbc.greenPlum.username");
        DB_PASSWORD = bundle.getString("jdbc.greenPlum.password");
        Class.forName("org.postgresql.Driver");
        // 获取连接
        logger.info("开始连接数据库：" + DB_URL + "，用户名为：" + DB_USER_NAME);
        conn = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
        logger.info("获取数据库连接成功");
        return conn;
    }

    public void closeConnection(Connection conn) {
        closeConnection(null,conn);
    }

    public void closeConnection(PreparedStatement pstm,Connection conn) {
        try {
            if (pstm != null) {
                pstm.close();
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
            logger.info("数据库关闭成功");
        } catch (SQLException e) {
            logger.error("资源释放发生异常");
        }
    }
}
